package com.buka.controller;

import cn.hutool.core.util.StrUtil;
import com.buka.common.BizCodeEnum;
import com.buka.constants.Constants;
import com.buka.service.impl.MailService;
import com.buka.util.CommonUtil;
import com.buka.util.JsonData;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.buka.constants.Constants.CAPTCHA_CODE_EXPIRED;

@RestController
@RequestMapping("api/notify/v1")
@Slf4j
public class NotifyController {

    @Resource
    MailService mailService;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    private Producer producer;

    @RequestMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        String text = producer.createText();
        log.info("验证码：{}",text);

        //存入数据库
        String redisKey =getCaptchaKey(request);

        redisTemplate.opsForValue().set(redisKey,text, CAPTCHA_CODE_EXPIRED, TimeUnit.MINUTES);

        BufferedImage image = producer.createImage(text);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     *  生成用户的唯一标识
     *
     */
    private String getCaptchaKey(HttpServletRequest request){
        String ipAddr = CommonUtil.getIpAddr(request);
        String ua = request.getHeader("User-Agent");
        //把ip 和 ua 拼接成字符换生成 MD5 减少长度
        String md5 = CommonUtil.MD5(ipAddr + ua);


        //为了清晰知道redis中key标识的是验证码 拼接一个字符换标识
        return "user:captcha:" + md5;
    }



    /**
     * 发送邮件验证码方法
     * 发送前需要验证图形验证码
     */
    @RequestMapping("send_code")
    public JsonData sendEmailCode(String code,String mail,HttpServletRequest request){
        //校验图验证码
        String captchaKey = getCaptchaKey(request);
        //图形验证码的值
        String old_code = (String) redisTemplate.opsForValue().get(captchaKey);
        if(null == old_code){
            return JsonData.buildError("验证码过期");
        }else if(StrUtil.equals(old_code,code)){
            return mailService.sendCode(mail,request);
        }else{
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA);
        }
    }
}
